<div class="layuimini-container">
    <div class="layui-form-item">
        <label class="layui-form-label">规格名</label>
        <div class="layui-input-block" id="specItem">
            
           
        </div>
    </div>
    <form action="" class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">规格：</label>
            <div class="layui-input-block">
                <table class="layui-table" id="spec-table">
                    <thead>
                        <tr>
                            <th>规格名</th>
                            <th>规格值</th>
                        </tr>
                    </thead>
                    <tbody>
                       
                    </tbody>
                </table>
            </div>
        </div>
        <div class="layui-form-item layui-hide">
            <label class="layui-form-label">批量设置：</label>
            <div class="layui-input-block">
                <table class="layui-table" id="sku-price"  lay-filter="sku-price">
                    <thead>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
        <div class="layui-form-item layui-hide">
            <label class="layui-form-label">SKU表：</label>
            <div class="layui-input-block">
                <table class="layui-table" id="sku-table">
                    <thead></thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
        
    </form>
</div>
<script>
 
layui.use(['form', 'upload', 'jquery','table'], function() {
    var form = layui.form,
        upload = layui.upload,
        $ = layui.jquery;
        var table = layui.table;

    function createSkuTable(url = '/admin/ajax/upload') {
        var specData = [];
        $.each($('#spec-table tbody tr'), function() {
            var child = [];
            $.each($(this).find('input[type=checkbox]'), function() {
                child.push({ id: $(this).val(), title: $(this).attr('title'), checked: $(this).is(':checked') });
            });
            var specItem = { id: $(this).find('td').eq(0).attr('data-id'), title: $(this).find('td').eq(0).text(), show: $(this).find('input[type=checkbox]:checked').length > 0, child: child };
            
            specData.push(specItem);
        });
        // console.log(specData)
        if ($('#spec-table tbody input[type=checkbox]:checked').length) {
            $('#sku-table').parent().parent().removeClass('layui-hide');
            $('#sku-price').parent().parent().removeClass('layui-hide');
            var prependThead = [],
                prependTbody = [];
            $.each(specData, function() {
                if (this.show) {
                    prependThead.push(this.title);
                    var prependTbodyItem = [];
                    $.each(this.child, function() {
                        if (this.checked) {
                            prependTbodyItem.push({ id: this.id, title: this.title });
                        }
                    });
                    prependTbody.push(prependTbodyItem);
                }
            });
            if (prependThead.length > 0) {
                $('#sku-table thead').html('<tr>' +
                    prependThead.map(function(t, i, a) {
                        return '<th>' + t + '</th>'
                    }) +
                    '<th>图片</th>' +
                    '<th>原价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                    '<th>活动价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                    '<th>库存 <i class="layui-icon layui-icon-cols"></i></th>' +

                    '</tr>');
                $('#sku-price thead').html('<tr><th>图片</th>' +
                    '<th>原价(元)</th>' +
                    '<th>活动价(元)</th>' +
                    '<th>库存 </th>' +
                    '<th>操作 </th>' +
                    '</tr>');
            }

            var prependTbodyTrs = [];
            var prependTbodyTrsPrice = [];
            // console.log(prependTbody)
            prependTbody.reduce(function(prev, cur, index, array) {
                var tmp = [];
                prev.forEach(function(a) {
                    cur.forEach(function(b) {
                        tmp.push({ id: a.id + ',' + b.id, title: a.title + ',' + b.title });
                    })
                });
                return tmp;
            }).forEach(function(item, index, array) {
                // console.log(item)
              var  attrCate="";
              var  attrCateMember="";
              var  attrCateActivity="";
              attrCate+='<input type="text" name="skus[' + item.id + '][price]" value="0" id="price'+index+'" class="layui-input" lay-verify="required|number" lay-reqtext="原价不能为空">' 
              attrCateActivity+='<input type="text" name="skus[' + item.id + '][activity_price]" id="activity_price'+index+'" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="活动价不能为空">'
                
                
                prependTbodyTrs.push('<tr>' +
                    item.title.split(',').map(function(t, i, a) {
                        return '<td>' + t + '</td>';
                    }) +
                    '<td><input type="hidden" name="skus[' + item.id + '][picture]" value=""><img src="__STATIC__/admin/images/sku-add.png" alt="sku图片"></td>' +
                    '<td>'+attrCate+'</td>' +
                    '<td>'+attrCateActivity+'</td>' +
                    '<td><input type="text" name="skus[' + item.id + '][stock]" value="99999" class="layui-input stock" id="stock'+index+'" lay-verify="required|number" lay-reqtext="库存不能为空"></td>' +
                    '</tr>');
            });
            attrCate="";
            attrCateActivity="";
            attrCate+='<input type="text" " value="0" class="layui-input"  lay-verify="required|number" lay-reqtext="原价不能为空">' 
            attrCateActivity+='<input type="text"  value="0"  class="layui-input" lay-verify="required|number" lay-reqtext="活动价不能为空">'
                
              prependTbodyTrsPrice.push('<tr ><td><input type="hidden"  value=""><img src="__STATIC__/admin/images/sku-add.png" alt="sku图片"></td>' +
                    '<td>'+attrCate+'</td>' +
                    '<td>'+attrCateActivity+'</td>' +
                    '<td><input type="text"  value="99999" class="layui-input" lay-verify="required|number" lay-reqtext="库存不能为空"></td>' +
                    '<td><a class="layui-btn layui-btn-xs layui-btn-success batchadd" onclick="batchadd()"  data-title="批量添加" >批量添加</a></td>' +
                    '</tr>');
            if (prependTbodyTrs.length > 0) {
                $('#sku-table tbody').html(prependTbodyTrs.join(''));
                $('#sku-price tbody').html(prependTbodyTrsPrice.join(''));
                $('input[name=spec]').val(JSON.stringify(specData));
                form.render();
                upload.render({
                    elem: '#sku-table td img',
                    url: url,
                    exts: 'png|jpg|ico|jpeg|gif',
                    accept: 'images',
                    acceptMime: 'image/*',
                    multiple: false,
                    done: function(res) {
                        if (res.code === 1) {
                            var url = res.data.url;
                            // console.log(url)
                            $(this.item).attr('src', url).prev().val(url);
                            layer.msg(res.msg);
                        } else {
                            layer.msg(res.msg);
                        }
                        return false;
                    }
                });
                upload.render({
                    elem: '#sku-price td img',
                    url: url,
                    exts: 'png|jpg|ico|jpeg|gif',
                    accept: 'images',
                    acceptMime: 'image/*',
                    multiple: false,
                    done: function(res) {
                        if (res.code === 1) {
                            var url = res.data.url;
                            // console.log(this.item)
                            $(this.item).attr('src', url).prev().val(url);
                            layer.msg(res.msg);
                        } else {
                            layer.msg(res.msg);
                        }
                        return false;
                    }
                });
            }
        } else {
            $('#sku-table').parent().parent().addClass('layui-hide');
            $('#sku-table thead').html('');
            $('#sku-table tbody').html('');
            $('#sku-price').parent().parent().addClass('layui-hide');
            $('#sku-price thead').html('');
            $('#sku-price tbody').html('');
            $('input[name=spec]').val('');
        }
    }

    /**
     * 初始化sku表
     */
    createSkuTable();
    
    /**
     * 监听sku表变化
     */
    form.on('checkbox(filter)', function(data) {
    
        createSkuTable();
    });

    /**
     * 监听批量赋值
     */
     $(document).on('click', '#sku-table thead tr th i', function() {
        var that = this;
        layer.prompt(function(value, index, elem) {
            $.each($('#sku-table tbody tr'), function() {
                $(this).find('td').eq($(that).parent().index()).children('input').val(value);
            });
            layer.close(index);
        });
    });
    /**
     * 监听表单提交
     */
    form.on('submit(submit)', function(data) {
        var state = Object.keys(data.field).some(function(item, index, array) {
            return item.startsWith('skus');
        });
        state ? layer.alert(JSON.stringify(data.field), { title: '提交的数据' }) : layer.msg('sku表数据不能为空', { icon: 5, anim: 6 });
        return false;
    });

    // 选择规格模板
    form.on('checkbox(specs)', function(data) {
            console.log(data)
        let dataId = $(this).attr('data-id')
        let title = $(this).attr('data-title')

        let hasId = $('#spec-table tbody').find('tr').hasClass('specs'+dataId)
        // console.log(hasId)
        if (hasId) {
            $('.specs'+dataId).remove()
            return false
        }
        let content = $(this).attr('content')

        let contentArr = content.split(',')

        let = input = ''
        for(var i in contentArr){
            input += '<input type="checkbox" title="'+contentArr[i]+'" lay-filter="filter" name="specs_value['+title+'][]" value="'+contentArr[i]+'">'
        }
        $('#spec-table tbody').append('<tr class="specs'+dataId+'"><td>'+title+'</td><td>'+input+'</td></tr>')
        form.render()
        createSkuTable()
    });
  

});
/*
批量赋值
*/
function batchadd(){
    var that=this;
    var picture=''
    var stock=0
    var price=[]
    var member_price=[]
    var activity_price=[]
    var price_show=0
    var member_show=0
    var activity_show=0
    //取值
    $.each($('#sku-price tbody tr').find("td"), function(index, value) {
 
                 switch (index) {
                    case 1:
                        price.push($(this).find('input').val())
                        break;
                    case 2:
                        activity_price.push($(this).find('input').val())
                    break; 
                        case 0:
                        picture=$(this).children('input').val()
                    break;
                    case 3:
                        stock=$(this).children('input').val()
                    break; 
                   
                }
                
    });
    
   //赋值
   $.each($('#sku-table tbody tr'), function(index, value) {
       var _this=this;
            $.each($(this).children('td'),function(i,v){
            
                if($(this).find('img').length>0){
                    if(picture){
                        $(this).find("input[type=hidden]").val(picture)
                        $(this).find('img').attr('src',picture)
                    } 
                }
                if($(this).find('#stock'+index).val()){
                    $(this).find('#stock'+index).val(stock)
                }
                if($(this).find('#price'+index)){
                    $(this).find('#price'+index).val(price[0])
                }

               
            });
           form.render('checkbox')
             
   });
   
}  
</script>